package com.diggerh.ch6asynctask.p2pooltask;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * @author diggerH
 * @date 2022-11-25
 */
@Slf4j
@Service
public class AsyncTaskService2 {
    public static final Random RANDOM = new Random();
    public static final int MAX_RANDOM_TIME_MILLIS = 10000;

    @Async("taskExecutor1")
    public CompletableFuture<String> doTask1(String taskInput) throws Exception {
        String taskId = "doTask1";
        return doTask(taskId, taskInput);
    }

    @Async("taskExecutor2")
    public CompletableFuture<String> doTask2(String taskInput) throws Exception {
        String taskId = "doTask2";
        return doTask(taskId, taskInput);
    }

    @Async("taskExecutor3")
    public CompletableFuture<String> doTask3(String taskInput) throws Exception {
        String taskId = "doTask3";
        return doTask(taskId, taskInput);
    }

    public CompletableFuture<String> doTask(String taskId, String taskInput) throws Exception {
        long threadId = Thread.currentThread().getId();
        log.info("threadId:{}, task {}, input:{}, begin ...", threadId, taskId, taskInput);
        long start = System.currentTimeMillis();
        Thread.sleep(RANDOM.nextInt(MAX_RANDOM_TIME_MILLIS));
        long end = System.currentTimeMillis();
        log.info("threadId:{}, task {}, input:{}, used：{} millis.", threadId, taskId, taskInput, end - start);
        return CompletableFuture.completedFuture("threadId:" + threadId
                + ", task " + taskId + ", input " + taskInput + " completed.");
    }
}